package com.example.project10;

import android.content.Context;
import java.util.List;

/**
 * 书籍管理器 - 业务逻辑层
 * 负责书籍相关的业务逻辑处理，分离数据访问和业务规则
 */
public class BookManager {
    private BookDao bookDao;
    private InputValidator validator;
    
    public BookManager(Context context) {
        this.bookDao = new BookDao(context);
        this.validator = new InputValidator();
        this.bookDao.open();
    }
    
    /**
     * 关闭数据库连接
     */
    public void close() {
        if (bookDao != null) {
            bookDao.close();
        }
    }
    
    /**
     * 添加书籍
     * @param bookNumber 书号
     * @param bookName 书名
     * @param userEmail 用户邮箱
     * @return 操作结果
     */
    public BookOperationResult addBook(String bookNumber, String bookName, String userEmail) {
        // 输入验证
        InputValidator.ValidationResult numberValidation = validator.validateBookNumber(bookNumber);
        if (!numberValidation.isValid()) {
            return BookOperationResult.failure(numberValidation.getErrorMessage());
        }
        
        InputValidator.ValidationResult nameValidation = validator.validateBookName(bookName);
        if (!nameValidation.isValid()) {
            return BookOperationResult.failure(nameValidation.getErrorMessage());
        }
        
        InputValidator.ValidationResult emailValidation = validator.validateUserEmail(userEmail);
        if (!emailValidation.isValid()) {
            return BookOperationResult.failure(emailValidation.getErrorMessage());
        }
        
        // 检查书号是否已存在
        if (isBookNumberExists(bookNumber, userEmail)) {
            return BookOperationResult.failure("该书号已存在");
        }
        
        // 创建书籍对象并保存
        Book book = new Book(bookNumber.trim(), bookName.trim(), userEmail);
        long result = bookDao.addBook(book);
        
        if (result != -1) {
            return BookOperationResult.success("添加成功");
        } else {
            return BookOperationResult.failure("添加失败，请重试");
        }
    }
    
    /**
     * 删除书籍
     */
    public BookOperationResult deleteBook(int bookId, String userEmail) {
        if (bookId <= 0) {
            return BookOperationResult.failure("无效的书籍ID");
        }
        
        InputValidator.ValidationResult emailValidation = validator.validateUserEmail(userEmail);
        if (!emailValidation.isValid()) {
            return BookOperationResult.failure(emailValidation.getErrorMessage());
        }
        
        int result = bookDao.deleteBook(bookId, userEmail);
        if (result > 0) {
            return BookOperationResult.success("删除成功");
        } else {
            return BookOperationResult.failure("删除失败，该书籍可能不存在");
        }
    }
    
    /**
     * 更新书籍信息
     */
    public BookOperationResult updateBook(Book book) {
        if (book == null || book.getId() <= 0) {
            return BookOperationResult.failure("无效的书籍信息");
        }
        
        InputValidator.ValidationResult numberValidation = validator.validateBookNumber(book.getBookNumber());
        if (!numberValidation.isValid()) {
            return BookOperationResult.failure(numberValidation.getErrorMessage());
        }
        
        InputValidator.ValidationResult nameValidation = validator.validateBookName(book.getBookName());
        if (!nameValidation.isValid()) {
            return BookOperationResult.failure(nameValidation.getErrorMessage());
        }
        
        // 检查书号是否与其他书籍冲突
        if (isBookNumberExistsExcluding(book.getBookNumber(), book.getUserEmail(), book.getId())) {
            return BookOperationResult.failure("该书号已被其他书籍使用");
        }
        
        // 规范化数据
        book.setBookNumber(book.getBookNumber().trim());
        book.setBookName(book.getBookName().trim());
        
        int result = bookDao.updateBook(book);
        if (result > 0) {
            return BookOperationResult.success("修改成功");
        } else {
            return BookOperationResult.failure("修改失败，请重试");
        }
    }
    
    /**
     * 获取用户的所有书籍
     */
    public List<Book> getUserBooks(String userEmail) {
        return bookDao.getAllBooksByUser(userEmail);
    }
    
    /**
     * 搜索书籍
     */
    public BookSearchResult searchBooks(String bookNumber, String bookName, String userEmail) {
        // 规范化搜索条件
        String normalizedNumber = bookNumber != null ? bookNumber.trim() : "";
        String normalizedName = bookName != null ? bookName.trim() : "";
        
        List<Book> books = bookDao.searchBooks(normalizedNumber, normalizedName, userEmail);
        
        if (books.isEmpty()) {
            return new BookSearchResult(books, "未找到符合条件的书籍");
        } else {
            return new BookSearchResult(books, "找到 " + books.size() + " 本书籍");
        }
    }
    
    /**
     * 为新用户初始化示例数据
     */
    public void initializeUserData(String userEmail) {
        List<Book> existingBooks = bookDao.getAllBooksByUser(userEmail);
        if (existingBooks.isEmpty()) {
            bookDao.addBook(new Book("978-7-5063-6543-7", "活着", userEmail));
            bookDao.addBook(new Book("978-7-5327-2294-2", "三体", userEmail));
            bookDao.addBook(new Book("978-7-02-000873-8", "围城", userEmail));
        }
    }
    
    /**
     * 检查书号是否已存在
     */
    private boolean isBookNumberExists(String bookNumber, String userEmail) {
        List<Book> books = bookDao.searchBooksByNumber(bookNumber, userEmail);
        return !books.isEmpty();
    }
    
    /**
     * 检查书号是否与其他书籍冲突（排除指定书籍）
     */
    private boolean isBookNumberExistsExcluding(String bookNumber, String userEmail, int excludeBookId) {
        List<Book> books = bookDao.searchBooksByNumber(bookNumber, userEmail);
        return books.stream().anyMatch(book -> book.getId() != excludeBookId);
    }
    
    /**
     * 书籍操作结果类
     */
    public static class BookOperationResult {
        private final boolean success;
        private final String message;
        
        private BookOperationResult(boolean success, String message) {
            this.success = success;
            this.message = message;
        }
        
        public static BookOperationResult success(String message) {
            return new BookOperationResult(true, message);
        }
        
        public static BookOperationResult failure(String message) {
            return new BookOperationResult(false, message);
        }
        
        public boolean isSuccess() {
            return success;
        }
        
        public String getMessage() {
            return message;
        }
    }
    
    /**
     * 书籍搜索结果类
     */
    public static class BookSearchResult {
        private final List<Book> books;
        private final String message;
        
        public BookSearchResult(List<Book> books, String message) {
            this.books = books;
            this.message = message;
        }
        
        public List<Book> getBooks() {
            return books;
        }
        
        public String getMessage() {
            return message;
        }
        
        public boolean isEmpty() {
            return books == null || books.isEmpty();
        }
    }
}